﻿using SF.Common;
using SF.Ucenter.shallWeChat;
using SF.Web.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.SessionState;

namespace SF.Ucenter.tools
{
    /// <summary>
    /// goods_ajax 的摘要说明
    /// </summary>
    public class goods_ajax : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            //检查管理员是否登录
            if (!new ManagePage().IsAdminLogin())
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"尚未登录或已超时，请登录后操作！\"}");
                return;
            }

            //取得处事类型
            string action = DTRequest.GetQueryString("action");
            switch (action)
            {
                case "goods_type_name_validate"://**验证商品分类名称是否重复
                    goods_type_name_validate(context);
                    break;
                case "goods_type_num_validate"://**验证商品分类编号是否重复
                    goods_type_num_validate(context);
                    break;
                case "goods_list_num_validate"://**验证商品编号是否重复
                    goods_list_num_validate(context);
                    break;
                case "get_color_size": //属性栏 控制
                    get_color_size(context);
                    break;
                case "save_amountlist": //存入 库存集合
                    save_amountlist(context);
                    break;
                case "upadte_express": //修改 打单
                    upadte_express(context);
                    break;
                case "edit_order_status": //修改 快递名称 或 物流单号
                    edit_order_status(context);
                    break;
            }
        }

        #region 修改 快递名称 或 物流单号
        private void edit_order_status(HttpContext context)
        {
            BLL.sf_goods_order orderInfoBll = new BLL.sf_goods_order();
            string orderid = DTRequest.GetFormString("order_no");
            string edit_type = DTRequest.GetFormString("edit_type");
            string remark = DTRequest.GetFormString("remark");
            Model.sf_goods_order order = orderInfoBll.GetModel(Convert.ToInt64(orderid));
            string msg = "",name = order.expressName,num = order.expressNum;
            if (edit_type.Equals("edit_order_express_name"))
            {
                order.expressName = remark.Trim();
                msg = "修改快递名称成功！";
            }
            else
            {
                order.expressNum = remark.Trim();
                msg = "修改物流单号成功！";
            }
            bool issuss = orderInfoBll.Update(order);
            //判断是否需要 发送模版消息
            if (issuss && order.isExpress>1)
            {
                if (!string.IsNullOrEmpty(order.expressName) && !string.IsNullOrEmpty(order.expressNum))
                {
                    if (order.expressName.Equals(name) && order.expressNum.Equals(num))
                    {
                    }
                    else
                    {
                        order.expressTime = DateTime.Now;
                        orderInfoBll.Update(order);
                        Model.sf_user_info userModel = new BLL.sf_user_info().GetModelByNum(order.userNum,Utils.getWhereByInfo(order.busnieseNum,order.appNum,order.templatesNum));
                        Model.sf_appidmanage appModel = new BLL.sf_appidmanage().GetModel(order.appNum);
                        DataTable detaldt = new BLL.sf_goods_orderdetal().GetList("orderNum='" + order.orderNum + "' and " + SF.Common.Utils.getWhereByInfo(order.busnieseNum, order.appNum, order.templatesNum)).Tables[0];
                        Model.sf_goods_info goods = new BLL.sf_goods_info().GetModel("goodsNum='" + detaldt.Rows[0]["goodsNum"] + "' and " + SF.Common.Utils.getWhereByInfo(order.busnieseNum, order.appNum, order.templatesNum));
                        if (detaldt.Rows.Count > 1)
                        {
                            goods.names = goods.names + "...";
                        }
                        IDictionary dict = ConfigurationManager.GetSection("weixinPay") as IDictionary;
                        string inf_uri = dict["inf_uri"].ToString();
                        string template_get = dict["template_get"].ToString();
                        string template_send = dict["template_send"].ToString();
                        api.wxpay.WebClient obj = new api.wxpay.WebClient();

                        string str1 = obj.GetHtml(inf_uri + "grant_type=client_credential&appid=" + appModel.appid + "&secret=" + appModel.appsecret);
                        wxaccesstoken ak = api.wxpay.JsonHelper.JsonDeserialize<wxaccesstoken>(str1);
                        string str2 = obj.Post(template_get + "access_token=" + ak.access_token, "{\"template_id_short\": \"OPENTM207847187\"}");
                        templateMsg tem = api.wxpay.JsonHelper.JsonDeserialize<templateMsg>(str2);

                        string temMsg = "您的商品【" + goods.names + "】已更改物流信息，请注意查收！";
                        if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(num))
                        {
                            temMsg = "您的商品【" + goods.names + "】已成功发出，请注意查收！";
                        }
                        string str3 = obj.Post(template_send + "access_token=" + ak.access_token, "{\"touser\":\"" + userModel.openID + "\",\"template_id\":\"" + tem.template_id + "\",\"url\":\"http://m.kuaidi100.com/result.jsp?nu="+order.expressNum+"\",\"data\":{\"first\":{\"value\":\"" + temMsg + "\",\"color\":\"#173177\"},\"keyword1\":{\"value\":\"" + order.orderNum + "\",\"color\":\"#173177\"},\"keyword2\":{\"value\":\"" + order.expressName + "\",\"color\":\"#173177\"},\"keyword3\":{\"value\":\"" + order.expressNum + "\",\"color\":\"#173177\"},\"keyword4\":{\"value\":\"" + DateTime.Now + "\",\"color\":\"#173177\"},\"remark\":{\"value\":\"感谢您的支持，欢迎您再次光临！点击查询\",\"color\":\"#173177\"}}}");
                        msg = msg + "发货提醒已推送";
                    }
                }
            }
            context.Response.Write("{\"status\": 1, \"msg\": \"" + msg + "\"}");
        }
        #endregion

        #region 修改 是否 打印运单
        private void upadte_express(HttpContext context)
        {
            BLL.sf_goods_order orderInfoBll = new BLL.sf_goods_order();
            string id = context.Request.QueryString["id"];
            bool issuss = orderInfoBll.UpdateExpress(Convert.ToInt32(id));
            context.Response.Write(issuss);
        }
        #endregion

        #region 存入 库存集合
        private void save_amountlist(HttpContext context)
        {
            Model.manager mgr = context.Session[DTKeys.SESSION_ADMIN_INFO] as Model.manager;
            string busnieseNum = mgr.busnieseNum.ToString();
            string appNum = context.Session[DTKeys.SESSION_APP_INFO].ToString();
            string templatesNum = context.Session[DTKeys.SESSION_TEMPLATES_INFO].ToString();

            string goodNum = context.Request.QueryString["goodsNum"];
            string list = context.Request.QueryString["str"];
            string[] strs = list.Substring(0, list.Length - 1).Split(',');
            BLL.sf_goods_amounts amountBll = new BLL.sf_goods_amounts();
            amountBll.Delete(" goodsNum='" + goodNum + "' and " + Utils.getWhereByInfo(busnieseNum, appNum, templatesNum));
            for (int i = 0; i < strs.Length; i++)
            {
                Model.sf_goods_amounts amount = new Model.sf_goods_amounts();
                amount.goodsNum = goodNum;
                amount.sizeId = Convert.ToInt32(strs[i].Split('^')[0]);
                amount.colorId = Convert.ToInt32(strs[i].Split('_')[1]);
                amount.amount = Convert.ToDecimal(strs[i].Split('_')[2]);
                amount.busnieseNum = busnieseNum;
                amount.appNum = appNum;
                amount.templatesNum = templatesNum;
                amountBll.Add(amount);
            }
        }
        #endregion

        #region 属性栏 控制
        private void get_color_size(HttpContext context)
        {
            Model.manager mgr = context.Session[DTKeys.SESSION_ADMIN_INFO] as Model.manager;
            string busnieseNum = mgr.busnieseNum.ToString();
            string appNum = context.Session[DTKeys.SESSION_APP_INFO].ToString();
            string templatesNum = context.Session[DTKeys.SESSION_TEMPLATES_INFO].ToString();

            string res = "";
            BLL.sf_goods_size sizeBll = new BLL.sf_goods_size();
            BLL.sf_goods_color colorBll = new BLL.sf_goods_color();
            string strs = context.Request.QueryString["id"];
            DataTable dtsize = sizeBll.GetList(" goodsTypeNum='" + strs + "' and " + Utils.getWhereByInfo(busnieseNum, appNum, templatesNum)).Tables[0];
            foreach (DataRow r in dtsize.Rows)
            {
                res += r["id"] + "_" + r["sizeName"] + ",";
            }
            res += "|";
            DataTable dtcolor = colorBll.GetList(" goodsTypeNum='" + strs + "' and " + Utils.getWhereByInfo(busnieseNum, appNum, templatesNum)).Tables[0];
            foreach (DataRow r in dtcolor.Rows)
            {
                res += r["id"] + "_" + r["colorName"] + "_" + r["goodsTypeNum"] + ",";
            }
            res = res == "|" ? "" : res;
            context.Response.Write(res);
        }
        #endregion

        #region 验证商品编号是否重复
        private void goods_list_num_validate(HttpContext context)
        {
            Model.manager mgr = context.Session[DTKeys.SESSION_ADMIN_INFO] as Model.manager;
            string busnieseNum = mgr.busnieseNum.ToString();
            string appNum = context.Session[DTKeys.SESSION_APP_INFO].ToString();
            string templatesNum = context.Session[DTKeys.SESSION_TEMPLATES_INFO].ToString();

            string navname = DTRequest.GetString("param");
            string old_name = DTRequest.GetString("old_name");
            if (string.IsNullOrEmpty(navname))
            {
                context.Response.Write("{ \"info\":\"该商品编号不可为空！\", \"status\":\"n\" }");
                return;
            }
            if (navname.ToLower() == old_name.ToLower())
            {
                context.Response.Write("{ \"info\":\"该商品编号可使用\", \"status\":\"y\" }");
                return;
            }
            BLL.sf_goods_info bll = new BLL.sf_goods_info();
            if (bll.Exists(navname, Utils.getWhereByInfo(busnieseNum, appNum, templatesNum)))
            {
                context.Response.Write("{ \"info\":\"该商品编号已被占用，请更换！\", \"status\":\"n\" }");
                return;
            }
            context.Response.Write("{ \"info\":\"该商品编号可使用\", \"status\":\"y\" }");
            return;
        }

        #endregion

        #region 验证商品分类名称是否重复
        private void goods_type_name_validate(HttpContext context)
        {
            Model.manager mgr = context.Session[DTKeys.SESSION_ADMIN_INFO] as Model.manager;
            string busnieseNum = mgr.busnieseNum.ToString();
            string appNum = context.Session[DTKeys.SESSION_APP_INFO].ToString();
            string templatesNum = context.Session[DTKeys.SESSION_TEMPLATES_INFO].ToString();

            string navname = DTRequest.GetString("param");
            string old_name = DTRequest.GetString("old_name");
            if (string.IsNullOrEmpty(navname))
            {
                context.Response.Write("{ \"info\":\"该分类名称不可为空！\", \"status\":\"n\" }");
                return;
            }
            if (navname.ToLower() == old_name.ToLower())
            {
                context.Response.Write("{ \"info\":\"该分类名称可使用\", \"status\":\"y\" }");
                return;
            }
            BLL.sf_goods_types bll = new BLL.sf_goods_types();
            if (bll.Exists(navname,Utils.getWhereByInfo(busnieseNum, appNum, templatesNum)))
            {
                context.Response.Write("{ \"info\":\"该分类名称已被占用，请更换！\", \"status\":\"n\" }");
                return;
            }
            context.Response.Write("{ \"info\":\"该分类名称可使用\", \"status\":\"y\" }");
            return;
        }
        #endregion

        #region 验证商品分类编号是否重复
        private void goods_type_num_validate(HttpContext context)
        {
            Model.manager mgr = context.Session[DTKeys.SESSION_ADMIN_INFO] as Model.manager;
            string busnieseNum = mgr.busnieseNum.ToString();
            string appNum = context.Session[DTKeys.SESSION_APP_INFO].ToString();
            string templatesNum = context.Session[DTKeys.SESSION_TEMPLATES_INFO].ToString();

            string navname = DTRequest.GetString("param");
            string old_name = DTRequest.GetString("old_name");
            if (string.IsNullOrEmpty(navname))
            {
                context.Response.Write("{ \"info\":\"该分类编号不可为空！\", \"status\":\"n\" }");
                return;
            }
            if (navname.ToLower() == old_name.ToLower())
            {
                context.Response.Write("{ \"info\":\"该分类编号可使用\", \"status\":\"y\" }");
                return;
            }
            BLL.sf_goods_types bll = new BLL.sf_goods_types();
            if (bll.ExistsNum(navname,Utils.getWhereByInfo(busnieseNum, appNum, templatesNum)))
            {
                context.Response.Write("{ \"info\":\"该分类编号已被占用，请更换！\", \"status\":\"n\" }");
                return;
            }
            context.Response.Write("{ \"info\":\"该分类编号可使用\", \"status\":\"y\" }");
            return;
        }
        #endregion

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}